package com.atguigu.juc.study.chapter03.cf.otherapi;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author : leimingchao
 * @date Date : 2022年06月11日 22:07
 */
public class CompletableFutureAPIDemo2 {

    public static void main(String[] args) {

        //方式二：
        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("11111");
            return 1;
        }, threadPool).thenApply(f -> {
            // int i = 10 / 0;
            System.out.println("222222");
            return f + 2;
        }).thenApply(f -> {
            System.out.println("33333333");
            return f + 3;
        }).whenComplete((v, e) -> {
            if (e == null) {
                System.out.println("-----计算结果：" + v);
            }
        }).exceptionally(e -> {
            e.printStackTrace();
            System.out.println(e.getMessage());
            return null;
        });

        System.out.println(Thread.currentThread().getName() + "-----主线程先去忙其他任务");


        //方式一：主线程不要立刻结束，否则CompletableFuture默认使用的线程池会立刻关闭
        // try {
        //     TimeUnit.SECONDS.sleep(2);
        // } catch (InterruptedException e) {
        //     e.printStackTrace();
        // }

        threadPool.shutdown();
    }
}
